import React, { useState, useCallback, useEffect, useMemo } from "react";
import { Checkbox } from "antd";
import { features } from "ali-react-table";
import { useSessionStorageState } from "ahooks";
/**
 *
 * @param {*} rowKey
 * @param {*} dataSource
 * @param {*} getRowsByIds 默认根据咯一rowKey返回行数据
 * @param {*} onChange (selectedRowKeys,selectedRows)=> void
 * @returns
 */
export const useMultiSelect = ({ rowKey, dataSource, footerDataSource, getRowsByIds, onChange }) => {
	const [allKeys, setAllKeys] = useState([]);

	const [checkedId, setCheckedId] = useState(null);
	const [checkedRow, setCheckedRow] = useState(null);
	const [checkedIds, setCheckedIds] = useState([]);
	const [checkedRows, setCheckedRows] = useState([]);
	const [isAllChecked, setIsAllChecked] = useState(false);
	const [isAnyChecked, setIsAnyChecked] = useState(false);

	const clearTableSelected = useCallback(() => {
		setCheckedId(null);
		setCheckedRow(null);
		setCheckedIds([]);
		setCheckedRows([]);
		setIsAllChecked(false);
		setIsAnyChecked(false);
	});

	useEffect(() => {
		setAllKeys(dataSource.map(row => row[rowKey]));
	}, [dataSource]);

	useEffect(() => {
		setIsAllChecked(checkedIds.length === allKeys.length && checkedIds.length > 0);
	}, [checkedIds, allKeys]);
	useEffect(() => {
		setIsAnyChecked(checkedIds.length > 0);
	}, [checkedIds, allKeys]);
	const getRowsByIdsFn = useCallback(
		ids => {
			if (typeof getRowsByIds === "function") return getRowsByIds(dataSource, ids);
			return dataSource.filter(e => ids.includes(e[rowKey]));
		},
		[dataSource, getRowsByIds]
	);

	const setIdsAndRows = useCallback(
		(ids, key, action) => {
			const rows = getRowsByIdsFn(ids);
			setCheckedIds(ids);
			setCheckedRows(rows);
			onChange && onChange(ids, rows, key, action);
		},
		[getRowsByIdsFn, setCheckedIds, setCheckedRows, onChange]
	);
	const setIdAndRow = useCallback(
		(id, key, action) => {
			const [row] = getRowsByIdsFn([id]);
			setCheckedId(id);
			setCheckedRow(row);
			setCheckedIds([id]);
			setCheckedRows([row]);

			onChange && onChange(id, row, key, action);
		},
		[getRowsByIdsFn, setCheckedId, setCheckedRow, setCheckedIds, setCheckedRows, onChange]
	);

	const onRowCheckChange = useCallback(
		(nextValue, key, keys, action) => {
			if (Array.isArray(nextValue)) {
				// 多选
				setIdsAndRows([...nextValue], key, action);
			} else {
				// 单选
				setIdAndRow(nextValue, key, action);
			}
		},
		[setIdsAndRows, setIdAndRow]
	);
	//
	// const title = useMemo(() => (
	// 	<Checkbox
	// 		checked={isAllChecked}
	// 		indeterminate={!isAllChecked && isAnyChecked}
	// 		onChange={e => {
	// 			const flag = e.target.checked;
	// 			setIdsAndRows(flag ? allKeys : []);
	// 		}}
	// 	/>
	// ));

	const multiSelectProps = {
		value: checkedIds,
		stopClickEventPropagation: true,
		highlightRowWhenSelected: true,
		checkboxPlacement: "start",
		onChange: onRowCheckChange,
		clickArea: "cell", // 'radio' | 'cell' | 'row'
		checkboxColumn: {
			lock: true,
			width: 60
			// title // 注释掉后，使用TableBase原来的全选
		}
	};
	const singleSelectProps = {
		value: checkedId,
		stopClickEventPropagation: true,
		highlightRowWhenSelected: true,
		radioPlacement: "start",
		onChange: onRowCheckChange,
		clickArea: "cell", // 'radio' | 'cell' | 'row'
		radioColumn: {
			lock: true,
			width: 60
		}
	};
	const treeSelectProps = {
		tree: dataSource.concat(footerDataSource),
		rootKey: "root",
		/** 父子节点选中状态是否不再关联。设置为 true 之后，父节点和子节点的 value 独立管理，不再联动 */
		checkStrictly: false,
		/**
		 * 定义选中时回填的方式，可选值:
		 * - 'all'(返回所有选中的节点)
		 * - 'parent'(父子节点都选中时只返回父节点)
		 * - 'child'(父子节点都选中时只返回子节点)
		 */
		checkedStrategy: "all",
		/** 复选框所在列的位置 */
		checkboxPlacement: "start",
		/** 点击事件的响应区域 */
		clickArea: "cell",
		/** 复选框所在列的 column 配置，可指定 width，lock, title, align, features 等属性 */
		checkboxColumn: { lock: true },
		/** 被选中时是否高亮整行 */
		highlightRowWhenSelected: true,
		/** 受控用法：当前选中的值   string[] */
		value: checkedIds,
		/** 非受控用法：默认选中的值   defaultValue?: string[]*/
		/** 受控用法：状态改变回调    (nextValue:string[]) */
		onChange: onRowCheckChange,
		/** 是否对触发 onChange 的 click 事件调用 event.stopPropagation() */
		stopClickEventPropagation: true,
		isDisabled: row => row[rowKey] === "footerDataSource"
		/** 是否禁用该节点的交互  isDisabled?(row: any): boolean */
		/** 是否让该节点对应的子树 与其父节点脱离联动 idDetached?(row: any): boolean */
	};

	const columnResizeProps = {
		/** 非受控用法：默认的列宽数组 */
		// defaultSizes?: number[]

		/** 受控用法：列宽数组 */
		// sizes?: number[]
		/** 受控用法：修改宽度的回调函数 */
		// onChangeSizes?(nextSizes: number[]): void

		/** 列的最小宽度，默认为 60 */
		// minSize?: number
		/** 如果列宽数组中没有提供有效的宽度，fallbackSize 将作为该列的宽度，默认为 150 */
		fallbackSize: 120
		/* 列的最大宽度，默认为 1000 */
		// maxSize?: number

		/** 是否在调整列宽时禁用 user-select，默认为 true */
		// disableUserSelectWhenResizing?: boolean

		/** 把手的背景色 */
		// handleBackground?: string
		/** 鼠标悬停时，把手的背景色 */
		// handleHoverBackground?: string
		/** 把手激活时的背景色 */
		// handleActiveBackground?: string
	};
	return {
		checkedIds,
		onRowCheckChange,
		// isAllChecked,
		// isAnyChecked,
		// allKeys,
		multiSelectProps,
		singleSelectProps,
		treeSelectProps,
		columnResizeProps,
		clearTableSelected,
		setTableSelect: setIdsAndRows
	};
};
